package com.game;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public abstract class ListTableActivity extends ListActivity {
	protected DBAdapter myDBAdapter;
	protected Cursor cursor;
	protected SimpleCursorAdapter cursorAdapter;
	protected int layoutId;
	protected String myTable;
	protected int [] TO_ITEM;
	
	protected abstract void intialize();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		intialize();
		setContentView(R.layout.dblistmain);
		myDBAdapter = ((txtGameApplication)this.getApplication()).getDatabaseAdapter();
		cursor = getListCursor(myTable);
		showListItems(cursor,myTable);
		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			
				goCalledActivity(cursor.getInt(cursor.getColumnIndex(DBAdapter._ID)));
				
			}
		});
			
	}
	
	private Cursor getListCursor(String tableName){
		Log.v("ListTableActivity",tableName);
		Cursor myCursor = myDBAdapter.getAllItemCursor(tableName);
		if(myCursor!=null)
		{
		startManagingCursor(myCursor);
		}
		return myCursor;

	}

	private void showListItems(Cursor cursor,String tableName){
		cursorAdapter = new SimpleCursorAdapter(this,layoutId,cursor,myDBAdapter.getFromList(tableName),TO_ITEM);
		setListAdapter(cursorAdapter);
	}
	
	private void goCalledActivity(int id){
		Intent returnIntent = new Intent();
		returnIntent.putExtra("ItemId",id);
		setResult(RESULT_OK,returnIntent);
		finish();
	}
	
}
